import { persist } from "zustand/middleware";
import { IUserParams, userLogin } from "@/api/user";
import create from "zustand";
import { NavigateFunction } from "react-router-dom";
//登录成功后下发的数据格式
interface UserInfoType {
  objectId: string;
  sessionToken: string;
  shortId: string;
  username: string;
  avatar: string;
}
interface UserState {
  userInfo: UserInfoType | null;
  isLoading: boolean;
  loginFetch: (params: IUserParams, navigate: NavigateFunction) => void;
  logout: () => void;
  updateInfo: (info: UserInfoType) => void;
}
export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      userInfo: null,
      isLoading: false,
      //登录
      loginFetch: async (params, navigate) => {
        set({ isLoading: true });
        let res = await userLogin(params);
        setTimeout(() => {
          set({ isLoading: false, userInfo: res.data });
          navigate(-1);
        }, 1000);
      },
      //退出登录
      logout() {
        set({ userInfo: null });
        useUserStore.persist.clearStorage();
      },
      //更新用户信息
      updateInfo(info) {
        set({ userInfo: info });
      },
    }),
    {
      name: "react-client-user-info",
    }
  )
);
